﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using UIT.ScrumTool.Service.Properties;

namespace UIT.ScrumTool.Service.Utilities
{
    /// <summary>
    /// file cau hinh ket noi sql
    /// </summary>
    public class ConfigConnection
    {
        public static string _config = "";

        private readonly string exePath = Path.Combine(
            Environment.CurrentDirectory, "UIT.ScrumTool.Service.exe");

        private Configuration cf;

        #region LoadStaticForm
        //show trang thai cau hinh
        public void LoadStaticForm(TextBox host, TextBox database, TextBox user, TextBox pass, TextBox port,
                                   TextBox portservice)
        {
            cf = ConfigurationManager.OpenExeConfiguration(exePath);
            host.Text = cf.AppSettings.Settings["host"].Value;
            database.Text = cf.AppSettings.Settings["database"].Value;
            user.Text = cf.AppSettings.Settings["userName"].Value;
            pass.Text = cf.AppSettings.Settings["password"].Value;
            port.Text = cf.AppSettings.Settings["port"].Value;
            portservice.Text = cf.AppSettings.Settings["portService"].Value;
        }
        #endregion

        #region SaveConfig
        //luu cau hinh ket noi
        public void SaveConfig(string host, string database, string user, string pass, string port, string portService)
        {
            cf.AppSettings.Settings.Remove("host");
            cf.AppSettings.Settings.Add("host", host);

            cf.AppSettings.Settings.Remove("database");
            cf.AppSettings.Settings.Add("database", database);

            cf.AppSettings.Settings.Remove("userName");
            cf.AppSettings.Settings.Add("userName", user);

            cf.AppSettings.Settings.Remove("password");
            cf.AppSettings.Settings.Add("password", pass);

            cf.AppSettings.Settings.Remove("port");
            cf.AppSettings.Settings.Add("port", port);

            cf.AppSettings.Settings.Remove("portService");
            cf.AppSettings.Settings.Add("portService", portService);

            cf.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            _config = @"server=" + host + "," + port + ";database=" + database + ";User ID=" + user + ";password=" +
                      pass + ";Trusted_Connection=False;";
            SaveConnectionString("ScrumToolBDConnectionString", _config);
            MessageBox.Show("Save sucess!", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        #endregion

        #region TestConnect
        // Kiem tra ket noi co thanh cong hay ko
        public int TestConnect(string host, string database, string user, string pass, string port)
        {
            _config = @"server=" + host + "," + port + ";database=" + database + ";User ID=" + user + ";password=" +
                      pass + ";Trusted_Connection=False;";
            var cn = new SqlConnection(_config);
            try
            {
                cn.Open();
            }
            catch
            {
                MessageBox.Show("Connection fail!", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                return -1;
            }
            if (cn.State == ConnectionState.Open)
                MessageBox.Show("Connection success!", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
            return 0;
        }
        #endregion 

        #region SaveConnectionString
        // luu ket noi xuong app.config
        public void SaveConnectionString(string connectionName, string newValue)
        {
            // Get the application configuration file.
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConnectionStringSettings csSetting = config.ConnectionStrings.ConnectionStrings[connectionName];
            if (csSetting == null & !connectionName.Contains(".Properties.Settings."))
            {
                string settingName = ".Properties.Settings." + connectionName;
                foreach (ConnectionStringSettings cs in config.ConnectionStrings.ConnectionStrings)
                {
                    if (cs.Name.EndsWith(settingName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        csSetting = cs;
                        connectionName = cs.Name;
                        break;
                    }
                }
            }
            if (csSetting != null)
            {
                csSetting.ConnectionString = newValue;
            }
            else
            {
                string provideName = "System.Data.SqlClient";
                csSetting = new ConnectionStringSettings(connectionName, newValue, provideName);
                config.ConnectionStrings.ConnectionStrings.Add(csSetting);
            }
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(connectionName);
            Settings.Default.Reload();
        }
        #endregion 
    }
}